package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 菜品数据与口味保存
     * @param dishDto
     */
    @PostMapping
    public R saveDish(@RequestBody DishDto dishDto ){
        //保存菜品数据
        dishService.save(dishDto);
        //保存菜品口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //判断是否选择了口味
        if (flavors !=null&&flavors.size()>0){
            //保存菜品口味的数据,需要注意:Dishflavor中是没有数据的
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDto.getId());
            }
            dishFlavorService.saveBatch(flavors);
        }
        //动态构造一个key
        String key = "dish"+dishDto.getCategoryId()+"_1";
        //清除缓存
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询菜品数据
     * @return
     */
    @GetMapping("/page")
    public R pageQuery (Integer page,Integer pageSize,String name){
        //创建page对象,设置当前页的和每页大小
        Page<Dish> pageInfo =new Page<>(page,pageSize);
        //封装查询条件
        LambdaQueryWrapper<Dish> qw =new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //封装排序
        qw.orderByDesc(Dish::getUpdateTime);
        //开始查询
        dishService.page(pageInfo,qw);
        //总条数
        long total = pageInfo.getTotal();
        Map map=new HashMap();
        map.put("total",total);
        //查询列表数据
        List<Dish> records = pageInfo.getRecords();
        //list<Dish> records--->List<DishDto> dishDtos
        List<DishDto> dishDtos=new ArrayList<>();
        //for循环的写法

       /* for (Dish record : records) {
            BeanUtil.copyProperties(record,dishDto);
            Long categoryId = record.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            dishDto.setCategoryName(byId.getName());
        }
       map.put("records",records);*/
        //拉姆达表达式写法
        dishDtos = records.stream().map(dish ->{
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(dish,dishDto);
            Long categoryId = dish.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            dishDto.setCategoryName(byId.getName());
            return dishDto;
        }).collect(Collectors.toList());
       map.put("records",dishDtos);
       return R.success(map);

    }


    /**
     * 根据id查询菜品信息和对应的口味
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getByIdWithFlavor ( @PathVariable Long id){
        //查询菜品基本信息,从dish表中查询
        Dish dish = dishService.getById(id);
        DishDto dishDto =new DishDto();
        BeanUtil.copyProperties(dish,dishDto);
        //查询当前菜品对应的口味信息，从dish_flavor表查询
        LambdaQueryWrapper<DishFlavor> qw =new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(qw);
        dishDto.setFlavors(flavors);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<DishDto> updateWithFlavor(@RequestBody DishDto dishDto){
        //更新dish表信息
        dishService.updateById(dishDto);
        //清理当前菜品对应的口味dish_flavor的delete操作
        LambdaQueryWrapper<DishFlavor>qw =new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(qw);
        //添加当前提交过的口味数据dish_flavor的update操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        //动态构造一个key
        String key = "dish"+dishDto.getCategoryId()+"_1";
        //清除缓存
        redisTemplate.delete(key);
        return R.success(null);

    /*    dishFlavorService.saveBatch(flavors);
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
        return R.success(null);*/

    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteDish(@RequestParam List<Long> ids){
        for (Long id : ids) {
            Long categoryId = dishService.getById(id).getCategoryId();
            if (categoryService.getById(categoryId).getType()!=1){

                return R.error("删除失败");
            }
        }
       dishService.removeByIds(ids);
        //动态构造一个key
        String key = "dish"+ids+"_1";
        //清除缓存
        redisTemplate.delete(key);
        return R.success("删除成功");
    /*    //先删除菜品的口味
        LambdaQueryWrapper<DishFlavor> qw =new LambdaQueryWrapper<>();
        qw.in(DishFlavor::getId,ids);
        dishFlavorService.remove(qw);
        //再删除菜品
        dishService.removeByIds(ids);
*/
    }

    /**
     * 起售,停售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status,
                          @RequestParam List<Long> ids){
        //TODO update dish set status = 前端给我啥就是啥，错了找前端
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }

        return R.success("操作成功");
    }

    /**
     * 根据分类id查询该分类下的所有菜品集合
     * @param
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> queryDishByCategoryId(Dish dish){
        List<DishDto> dishDtoList=null;
        //动态构造key
        String key ="dish"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList!=null){
            //如果存在,直接返回,不需调查数据库
            return R.success(dishDtoList);
        }
        //如果不存在
        //构造查询条件
        LambdaQueryWrapper<Dish> qw =new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,dish.getCategoryId());
        qw.eq(Dish::getStatus,1);
//        //添加条件,查询状态为1
//        qw.eq(Dish::getStatus,1);
        //添加排序条件
        qw.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(qw);
        //List<Dish>--->List<DishDto>
         dishDtoList = new ArrayList<>();
        for (Dish dish1 : list) {
            DishDto dishDto =new DishDto();
            //菜品的数据
            BeanUtil.copyProperties(dish1,dishDto);
            //菜品的口味数据 select * from dish_flavor where dish_id =?
            LambdaQueryWrapper<DishFlavor> qwl = new LambdaQueryWrapper<>();
            qwl.eq(DishFlavor::getDishId,dish1.getId());
            List<DishFlavor> list1 = dishFlavorService.list(qwl);
            dishDto.setFlavors(list1);
            dishDtoList.add(dishDto);
        }
        //如果不存在,需要查询数据库并将查询到的菜品添加到redis缓存中
        redisTemplate.opsForValue().set(key,dishDtoList,5, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}
